package com.jyniubi.gmall.scheduled.jobHandler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jyniubi.gmall.cart.entity.CartEntity;
import com.jyniubi.gmall.cart.mapper.CartMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Slf4j
public class CartJobHandler {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CartMapper cartMapper;
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final String EXCEPTION_KEY = "cart:exception";
    private static final String KEY_PREFIX = "cart:info:";

    @XxlJob("cartJobHandler")
    public ReturnT<String> execute(String param) {
        // 1. 读取失败信息 -redis
        BoundSetOperations<String, String> setOps = this.redisTemplate.boundSetOps(EXCEPTION_KEY);
        // 随机从redis错误信息中获取一个userId
        String userId = setOps.pop();
        // 2. 判空，如果为空直接结束
        while (userId != null){
            // 3. 将对应用户mysql中的购物车信息全部删掉
            this.cartMapper.delete(new QueryWrapper<CartEntity>().eq("user_id", userId));
            // 4. 然后看对应用户失败信息是否为空，为空则结束
            BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
            List<Object> cartJsons = hashOps.values();
            // 如果购物车信息为空，则获取下一个用户id，继续执行循环
            if (CollectionUtils.isEmpty(cartJsons)){
                userId = setOps.pop();
                continue;
            }
            // 5. 如果不为空，则需要新增到mysql
            cartJsons.forEach(cartJson->{
                CartEntity cartEntity = null;
                try {
                    cartEntity = MAPPER.readValue(cartJson.toString(), CartEntity.class);
                } catch (JsonProcessingException e) {
                    log.error("读取redis购物车失败信息json转购物车对象异常",e);
                }
                this.cartMapper.insert(cartEntity);
            });
            // 获取下一个用户id
            userId = setOps.pop();
        }
        //XxlJobLogger.log("我的任务执行了：" + param + "，线程：" + Thread.currentThread().getName());
        return ReturnT.SUCCESS;
    }
}
